import React, { useReducer } from "react";

// useReducer用来创建一个简易版本的redux仓库的

// 创建一个全局的仓库的初始数据
const defaultState = {
  name: "tom",
  age: 20,
};

// 创建了一个修改全局数据的方法
// action是一个包含type属性的对象
const reducer = (state, action) => {
  switch (action.type) {
    case "add":
      // 返回一个新对象，去覆盖老对象
      return {
        ...state,
        age: state.age + 1,
      };
    case "minus":
      return {
        ...state,
        age: state.age - 1,
      };
    case "nameChange":
      return {
        ...state,
        name: action.name,
      };
    default:
      return state;
  }
};

const Child = () => {
  const [state] = useReducer(reducer, defaultState);

  return <div>child组件 - {state.age}</div>;
};

const App = () => {
  // useReducer需要传入两个参数
  // 返回一个数组
  const [state, dispatch] = useReducer(reducer, defaultState);
  return (
    <>
      <h2>useReducer</h2>
      <div>name: {state.name}</div>
      <div>age: {state.age}</div>
      <button onClick={() => dispatch({ type: "add" })}>age++</button>
      <button
        onClick={() => dispatch({ type: "nameChange", name: "zhangsan" })}
      >
        changeName
      </button>

      <hr />

      <Child />
    </>
  );
};

export default App;
